package controller

import (
	"../model"
	"../service"
	"../utils"
	"fmt"
	"log"
	"math/rand"
	"net/http"
)

var userService *service.UserService

/**
 * 用户登录
 */
func Login(writer http.ResponseWriter, request *http.Request) {

	// 解析参数
	err := request.ParseForm()
	if err != nil {
		log.Fatal(err.Error())
	}
	// 获取参数
	mobile := request.Form.Get("mobile")
	plainPasswd := request.Form.Get("passwd")

	user, err := userService.Login(mobile, plainPasswd)
	if err != nil {
		utils.WriteResult(writer, -1001, nil, err.Error())
	} else {
		utils.WriteResult(writer, 0, user, "")
	}
}

// 注册
func Register(writer http.ResponseWriter, request *http.Request) {

	err := request.ParseForm()
	if err != nil {
		log.Fatal(err.Error())
	}

	// 获取参数
	mobileNumber := request.Form.Get("mobile")
	password := request.Form.Get("passwd")
	nickName := fmt.Sprintf("user%06d", rand.Int31n(1000000))
	avatar := ""
	sex := model.SEX_MALE

	user, err := userService.Register(mobileNumber, password, nickName, avatar, sex)
	if err != nil {
		utils.WriteResult(writer, -1, nil, err.Error())
	} else {
		utils.WriteResult(writer, 0, user, "")
	}
}
